package com.wuxi.zhang.design.factorypattern;

import java.io.File;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;

/**
 * @author zhang on 2018/12/20.
 */
public class PackageUtils {

    /**
     * 获取某包下所有类
     *
     * @return 类的完整名称
     */
    public static Set<String> getClassName() {
        Set<String> classNames;
        //包名
        String packageName = "com.wuxi.zhang.design.factorypattern.company";
        //获取类加载器
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        //包名路径
        String packagePath = packageName.replace(".", "/");
        URL url = loader.getResource(packagePath);
        //从项目文件获取某包下所有类
        classNames = getClassNameFromDir(url.getPath(), packageName);

        return classNames;
    }

    /**
     * 从项目文件获取某包下所有类
     *
     * @param filePath 文件路径
     * @return 类的完整名称
     */
    private static Set<String> getClassNameFromDir(String filePath, String packageName) {
        Set<String> className = new HashSet<String>();
        File file = new File(filePath);
        File[] files = file.listFiles();
        for (File childFile : files) {
            String fileName = childFile.getName();
            if (fileName.endsWith(".class") && !fileName.contains("$")) {
                className.add(packageName + "." + fileName.replace(".class", ""));
            }
        }
        return className;
    }


    public static void main(String[] args) {
        Set<String> classNames = getClassName();
        if (classNames != null) {
            for (String className : classNames) {
                System.out.println(className);
            }
        }
    }
}
